package service;
import java.util.List;

import com.jfinal.ext.kit.DateKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import common.kit.PageSql;
import model.Company;
import model.RunRecords;
import model.Staff;
import model.Station;

public class RunRecordsService extends BaseService {

	public Page<Record> getApiPage(Kv kv , Integer pageNumber , Integer pageSize) {
		String select = " trr.id,trr.createTime,trr.type,trr.startTime,trr.endTime,trr.recorder,trr.pics,tsc.name AS servicerName " ;
	    PageSql pageSql = PageSql.bySelect( kv , select ) ;
	    pageSql.from(" t_run_records trr ") ;
	    pageSql.join("t_servicer tsc", "tsc.id = trr.servicerId");
		pageSql.setNotLessThanCondition("trr.createTime","trr.createTime.start") ; //创建时间
		pageSql.setNotMoreThanCondition("trr.createTime","trr.createTime.end") ; //创建时间
		pageSql.setEqualCondition("trr.stationId") ; //站点
		pageSql.setEqualCondition("trr.realType") ;
	    pageSql.orderBy(" trr.createTime DESC ");
		Page<Record> page = pageSql.paginate( pageNumber , pageSize) ;
		List<Record> list = page.getList();
		for (Record record : list) {
			record.set("createTime", DateKit.toStr(record.getDate("createTime") , "yyyy-MM-dd HH:mm"));
			record.set("startTime", DateKit.toStr(record.getDate("startTime"), "yyyy-MM-dd HH:mm"));
			record.set("endTime", DateKit.toStr(record.getDate("endTime"), "yyyy-MM-dd HH:mm"));
		}
		return page ;
	}
	
	public Ret save(RunRecords runRecords , Staff staff , Station station) {
		runRecords.setStationId(station.getId());
		runRecords.setServicerId(staff.getServicerId());
		runRecords.setRecorder(staff.getName());
		runRecords.save();
		
		if (runRecords.isRunRealType()) {
			StationService service = new StationService() ;
			service.changeRunStatus(station);
			service.changeCompanyStatus(Company.dao.findById(station.getCompanyId()));
		}
		
		return ok() ;
	}
	
}
